package top.spring.study.config;

import com.google.common.collect.ImmutableMap;
import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Servlet;
import javax.servlet.ServletRegistration;
import java.util.HashMap;
import java.util.Map;

/**
 * 实现代理服务功能，思路是：客户端发送请求，由代理服务端通过端口监听到请求，然后在作为代理去访问真实的服务器，
 * 最后由真实的服务器将响应返回给代理，代理再返回给浏览器。
 * https://blog.csdn.net/zdx1515888659/article/details/109217480
 */

@Configuration
public class ProxyServletConfiguration {

    @Value("${proxy.servlet_url}")
    private String servletUrl;
    @Value("${proxy.target_url}")
    private String targetUrl;

    @Bean
    public Servlet proxyServlet(){
        return new ProxyServlet();
    }

    @Bean
    public ServletRegistrationBean proxyServletRegistration(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(proxyServlet(),servletUrl);
        Map<String,String> params = ImmutableMap.of(
                "targetUri", targetUrl,
                "log", "true");
        registrationBean.setInitParameters(params);
        // 多个时候，名称不一样
        registrationBean.setName("proxyBaidu");
        return registrationBean;
    }



}
